package sda.app_01.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.http.AjaxCallBack;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;

import sda.app_01.R;

/**
 * Created by scorpio on 15-3-18.
 */
public class fragment_2 extends Fragment {

    @ViewInject(id = R.id.tv_page)
    TextView tv_page;

    int position;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_2, null);
        FinalActivity.initInjectedView(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        position = getArguments().getInt("position");
        setUp();

        switch (position){
            case 1:
                new Thread(){
                    @Override
                    public void run() {
                        super.run();
                        loadData();
                    }
                }.start();
                break;
            case 2:
                AfinalHttp();
                break;
            case 3:
                break;
        }


    }

    private void AfinalHttp() {
        FinalHttp fh = new FinalHttp();
        fh.get("http://meiriyiwen.com/random", new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                String str = (String) o;
                tv_page.setText(Html.fromHtml(str));
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    // 自带的请求方法
    private void loadData(){
        String path = "https://www.baidu.com";
        // 请求的参数转换为byte数组
        String params = null;
        try {
            params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
                    + "&pwd=" + URLEncoder.encode("android", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] postData = params.getBytes();
        // 新建一个URL对象
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection urlConn = null;
            try {
                urlConn = (HttpURLConnection) url.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 设置连接超时时间
            urlConn.setConnectTimeout(5 * 1000);
            // Post请求必须设置允许输出
            urlConn.setDoOutput(true);
            // Post请求不能使用缓存
            urlConn.setUseCaches(false);
            // 设置为Post请求
            try {
                urlConn.setRequestMethod("POST");
            } catch (ProtocolException e) {
                e.printStackTrace();
            }
            urlConn.setInstanceFollowRedirects(true);
            // 配置请求Content-Type
            urlConn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencode");
            // 开始连接
            urlConn.connect();
            // 发送请求参数
            DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
            dos.write(postData);
            dos.flush();
            dos.close();
            // 判断请求是否成功
            if (urlConn.getResponseCode()==200){
                InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
                ByteArrayOutputStream bao = new ByteArrayOutputStream() ;
                int len = 0 ;
                byte[] buffer = new byte[1024];
                InputStream is = urlConn.getInputStream();
                while ((len = is.read(buffer)) != -1)
                {
                    bao.write(buffer, 0, len);
                }
                is.close();
                bao.close();
                byte[] res = bao.toByteArray();
                Log.d("请求到数据",new String(res));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setUp() {
        tv_page.setText("Page_" + position);

    }




}
